//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.saasovation.agilepm.port.adapter.messaging.rabbitmq;

import java.util.Date;
import java.util.Properties;

import com.saasovation.agilepm.application.product.ProductApplicationService;
import com.saasovation.agilepm.application.product.StartDiscussionInitiationCommand;
import com.saasovation.agilepm.port.adapter.messaging.ProductDiscussionExclusiveOwnerId;
import com.saasovation.common.notification.NotificationReader;
import com.saasovation.common.port.adapter.messaging.Exchanges;
import com.saasovation.common.port.adapter.messaging.rabbitmq.ConnectionSettings;
import com.saasovation.common.port.adapter.messaging.rabbitmq.Exchange;
import com.saasovation.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.saasovation.common.port.adapter.messaging.rabbitmq.MessageParameters;
import com.saasovation.common.port.adapter.messaging.rabbitmq.MessageProducer;
import com.saasovation.common.serializer.PropertiesSerializer;

/**
 * RabbitMQ产品讨论已请求监听器
 * @author learn
 */
public class RabbitMQProductDiscussionRequestedListener
        extends ExchangeListener {
    /**
     * 命令常量
     */
    private static final String COMMAND =
            "com.saasovation.collaboration.discussion.CreateExclusiveDiscussion";

    /**
     * 产品应用服务
     */
    private ProductApplicationService productApplicationService;

    /**
     * 由产品应用服务构造：RabbitMQ产品讨论已请求监听器
     * @param aProductApplicationService        产品应用服务
     */
    protected RabbitMQProductDiscussionRequestedListener(
            ProductApplicationService aProductApplicationService) {

        super();

        this.productApplicationService = aProductApplicationService;
    }
    /**
     * 获取回答监听到的交换名
     * @return      返回字符串
     */
    @Override
    protected String exchangeName() {
        return Exchanges.AGILEPM_EXCHANGE_NAME;
    }
    /**
     * 已删选的分配
     * @param aType the String message type
     * @param aTextMessage the String raw text message being handled
     */
    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        // 通知阅读器
        NotificationReader reader = new NotificationReader(aTextMessage);
        // 取出布尔值，如果为假就返回
        if (!reader.eventBooleanValue("requestingDiscussion")) {
            return;
        }
        // 使用此阅读器读取对应的值
        String tenantId = reader.eventStringValue("tenantId.id");
        String productId = reader.eventStringValue("product.id");
        // 使用产品应用服务来开始讨论发起
        this.productApplicationService.startDiscussionInitiation(
                new StartDiscussionInitiationCommand(
                        tenantId,
                        productId));
        // 从阅读器获得参数
        Properties parameters = this.parametersFrom(reader);
        // 建立属性序列化器
        PropertiesSerializer serializer = PropertiesSerializer.instance();
        // 把参数进行序列化
        String serialization = serializer.serialize(parameters);
        // 从参数建立命令ID
        String commandId = this.commandIdFrom(parameters);
        // 使用消息生产者发送后，然后关闭
        this.messageProducer()
            .send(
                serialization,
                MessageParameters
                    .durableTextParameters(
                            COMMAND,
                            commandId,
                            new Date()))
            .close();
    }
    /**
     * 监听...
     * @return      返回字符串数组
     */
    @Override
    protected String[] listensTo() {
        return new String[] {
                "com.saasovation.agilepm.domain.model.product.ProductCreated",
                "com.saasovation.agilepm.domain.model.product.ProductDiscussionRequested"
                };
    }

    /**
     * 由属性清单获取命令ID
     * @param aProperties       属性清单
     * @return                  返回字符串
     */
    private String commandIdFrom(Properties aProperties) {
        String commandId =
                aProperties.getProperty("tenantId")
                + ":"
                + aProperties.getProperty("productId");

        return commandId;
    }

    /**
     * 获取消息生产者
     * @return      返回消息生产者
     */
    private MessageProducer messageProducer() {

        // 扇出交换
        Exchange exchange =
            Exchange.fanOutInstance(
                    ConnectionSettings.instance(),
                    Exchanges.COLLABORATION_EXCHANGE_NAME,
                    true);

        // 建立消息生产者
        MessageProducer messageProducer =
                MessageProducer.instance(exchange);

        return messageProducer;
    }

    /**
     * 由阅读器获取参数属性
     * @param aReader       通知阅读器
     * @return              属性清单
     */
    private Properties parametersFrom(NotificationReader aReader) {
        Properties properties = new Properties();
        // 依次往属性清单放置：对应的值
        properties.put("command", COMMAND);

        properties.put("tenantId",
                aReader.eventStringValue("tenantId.id"));

        ProductDiscussionExclusiveOwnerId exclusiveOwnerId =
                new ProductDiscussionExclusiveOwnerId(
                        aReader.eventStringValue("productId.id"));

        properties.put("exclusiveOwnerId",
                exclusiveOwnerId.encoded());

        properties.put("forumSubject",
                "ProjectOvation Forum: " + aReader.eventStringValue("name"));

        properties.put("forumDescription",
                "About: " + aReader.eventStringValue("description"));

        properties.put("discussionSubject",
                "Product Discussion: " + aReader.eventStringValue("name"));

        String productOwnerId =
                aReader.eventStringValue("productOwnerId.id");

        properties.put("creatorId", productOwnerId);

        properties.put("moderatorId", productOwnerId);

        return properties;
    }
}
